import {
	fetchPerson
} from '../../../services/usercenter/fetchPerson';
import {
	phoneEncryption
} from '../../../utils/util';

import Toast from 'tdesign-miniprogram/toast/index';
const $api = require('../../../utils/request').Api;
Page({
	data: {
		personInfo: {
			avatarUrl: '',
			nickName: '',
			gender: 0,
			phoneNumber: '',
		},
		showUnbindConfirm: false,
		pickerOptions: [{
				name: '男',
				code: '1',
			},
			{
				name: '女',
				code: '2',
			},
		],
		typeVisible: false,
		genderMap: ['', '男', '女'],
		pnon: ''
	},
	onLoad() {
		this.init();
	},
	init() {
		this.fetchData();
	},
	fetchData() {
		fetchPerson().then((personInfo) => {
			const phon = wx.getStorageSync('userTel')
			console.log(phon);
			this.setData({
				personInfo,
				// pnon: phoneEncryption(phon),
				'personInfo.phoneNumber': phoneEncryption(phon.data),
			});
		});
	},
	onClickCell({
		currentTarget
	}) {
		console.log(currentTarget);
		const {
			dataset
		} = currentTarget;
		const {
			nickName
		} = this.data.personInfo;
		console.log(dataset.type);
		switch (dataset.type) {
			case 'gender':
				this.setData({
					typeVisible: true,
				});
				break;
			case 'name':
				wx.navigateTo({
					url: `/pages/usercenter/name-edit/index?name=${nickName}`,
				});
				break;
			case 'avatarUrl':
				this.toModifyAvatar();
				break;
			case 'phoneNumber':
				this.getPhoneNumber();
				break;
			default: {
				break;
			}
		}
  },

	onClose() {
		this.setData({
			typeVisible: false,
		});
	},
	onConfirm(e) {
		const {
			value
		} = e.detail;
		this.setData({
				typeVisible: false,
				'personInfo.gender': value,
			},
			() => {
				Toast({
					context: this,
					selector: '#t-toast',
					message: '设置成功',
					theme: 'success',
				});
			},
		);
	},
	async toModifyAvatar() {
		try {
			const tempFilePath = await new Promise((resolve, reject) => {
				wx.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const {
							path,
							size
						} = res.tempFiles[0];
						if (size <= 10485760) {
							resolve(path);
						} else {
							reject({
								errMsg: '图片大小超出限制，请重新上传'
							});
						}
					},
					fail: (err) => reject(err),
				});
			});
			const tempUrlArr = tempFilePath.split('/');
			const tempFileName = tempUrlArr[tempUrlArr.length - 1];
			Toast({
				context: this,
				selector: '#t-toast',
				message: `已选择图片-${tempFileName}`,
				theme: 'success',
			});
		} catch (error) {
			if (error.errMsg === 'chooseImage:fail cancel') return;
			Toast({
				context: this,
				selector: '#t-toast',
				message: error.errMsg || error.msg || '修改头像出错了',
				theme: 'error',
			});
		}
	},
	getPhoneNumber(e) {
		console.log(e)
		// if (e.detail.code) {
		wx.showLoading({ // 显示加载中loading效果 
			title: "加载中.....",
			mask: true //开启蒙版遮罩
		});
		this.login(e.detail.code)
		// }
	},
	//授权登录
	login(e) {
		let that = this
		wx.getSetting({
			success(res) {
				console.log(res.authSetting);
				if (res.authSetting['scope.userInfo'] === true) {
					that.shlogin(e);
					// wx.authorize({
					//   scope: 'scope.userInfo',
					//   success(resaut) {
					//     console.log(resaut);
					//     // 用户已经同意授权

					//   }
					// })
				} else {
					wx.showModal({
						title: '授权提示',
						content: '小程序需要您的微信授权才能使用哦~ 错过授权页面的处理方法：1.删除小程序->重新搜索进入->点击授权按钮。2.请点击确认跳转到设置页开启',
						success(res) {
							if (res.confirm) {
								wx.openSetting({
									success(res) {
										console.log(res.authSetting)
										// res.authSetting = {
										//   "scope.userInfo": true,
										//   "scope.userLocation": true
										// }
									}
								})
							} else if (res.cancel) {
								console.log('用户点击取消')
							}
						}
					})
				}
			}
		})
	},

	shlogin(e) {
		let that = this
		wx.login({
			success(rescode) {
				console.log(rescode);
				if (e) {
					try {
						// console.log('hhhhh');
						$api.login({
							code: rescode.code
						}).then((res) => {
							wx.setStorageSync('login', res)
							console.log(res);
							// wx.setStorageSync('user', user)
							// var userphone = res.data.data //解密手机号
							// var msg = e.detail.errMsg;
							// var sessionKey = userphone.session_key; //会话密钥  
							// var encryptedData = e.detail.encryptedData; //签名
							// var unionid = userphone.unionid //唯一标识
							// var iv = e.detail.iv; //授权成功
							if (res.statusCode == 200) {
								that.deciyption(e, res);
							}
						})
					} catch {
						wx.showToast({ // 显示加载中loading效果 
							title: "请重新登录",
							icon: 'error',
							duration: 3000
						});
					}
					// wx.request({
					//   url: 获取用户信息的auth.code2Session微信api接口,
					//   method: 'POST',
					//   data: {
					//     code: code //登录凭证code
					//   },
					//   header: {
					//     'content-type': 'application/json;charset=UTF-8'
					//   },
					//   success: function (res) {

					//   }
					// })
					// wx.getUserProfile({
					//   success: resuser => {
					//     let user = resuser.userInfo
					//     //设置本地缓存,把用户信息缓存到本地
					//     wx.setStorageSync('user', user)
					//     console.log('用户信息', user)
					//     userInfo = {
					//       avatarUrl: user.avatarUrl,
					//       nickName: user.nickName,
					//       phoneNumber: user.phoneNumber,
					//       gender: user.gender,
					//     }
					//     console.log(userInfo);
					//   }
					// })
				} else {
					console.log('登录失败！' + res.errMsg)
				}
			}
		})
	},

	deciyption(e, index) {
		console.log(index);
		$api.getUsePhone({
			code: e,
			openid: index.data.data.openid
		}).then((res) => {
			console.log(res);
			let data = res.data
			if (res.data.code == 1) {
				wx.setStorageSync('userTel', res.data); //存储解密后的用户手机号
				wx.switchTab({
					url: 'pages/usercenter/index'
				})
				wx.showToast({
					title: '绑定成功',
					icon: 'none',
					duration: 3000
				})
				this.setData({
					'personInfo.phoneNumber': phoneEncryption(res.data.data),
				});
			} else {
				wx.showToast({
					title: '获取信息失败请重新授权',
					icon: 'error',
					duration: 3000
				})
			}
		})
		// $api.loginsssssssssssssssssssssssss({
		// 	data: {
		// 		sessionKey: sessionKey,
		// 		encryptedData: encryptedData,
		// 		iv: iv
		// 	}
		// }).then((res) => {
		// 	let data = res.data
		// 	if (data.resultCode == 'success') {
		// 		wx.setStorageSync('userTel', data.data.phoneNumber); //存储解密后的用户手机号
		// 		wx.switchTab({
		// 			url: 'pages/usercenter/index'
		// 		})
		// 	} else {
		// 		wx.showToast({
		// 			title: '获取信息失败请重新授权',
		// 			icon: 'error',
		// 			duration: 3000
		// 		})
		// 	}
		// })
		// wx.request({
		//   url: 解密接口,
		//   method: 'POST',
		//   data: {
		//     sessionKey: sessionKey,
		//     encryptedData: encryptedData,
		//     iv: iv
		//   },
		//   header: {
		//     'content-type': 'application/json;charset=UTF-8'
		//   },
		//   success: function (res) {
		//     let data = res.data
		//     if (data.resultCode == 'success') {
		//       wx.setStorageSync('userTel', data.data.phoneNumber); //存储解密后的用户手机号
		//     } else {
		//       wx.showToast({
		//         title: '获取信息失败请重新授权',
		//         icon: 'none'
		//       })
		//       that.setData({
		//         isShow: true
		//       })
		//     }
		//   },
		//   fail: function (res) {
		//     wx.showToast({
		//       title: '获取失败请重新授权',
		//       icon: 'none'
		//     })
		//     that.setData({
		//       isShow: true
		//     })
		//   }
		// })
	},
});